package com.kuang.exam.core.utils.file;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Oss工具类
 *
 */
//@Component
@Slf4j
public class OssUtil {

    /**
     * 地域节点
     */
    @Value("${aliyun.oss.end.point}")
    private String endpoint;
    /**
     * AccessKey ID
     */
    @Value("${aliyun.oss.access.key.id}")
    private String accessKeyId;
    /**
     * Access Key Secret
     */
    @Value("${aliyun.oss.access.key.secret}")
    private String accessKeySecret;
    /**
     * 仓库名称
     */
    @Value("${aliyun.oss.bucket.name}")
    private String bucketName;

    /**
     * 文件存储目录
     */
    private String fileDir = "Avatar/";

    /**
     * 单个文件上传
     *
     * @param file 上传的文件
     * @return 返回完整URL地址
     */
    public String uploadFile(MultipartFile file) {
        String fileUrl = uploadImgToOss(file);
        String str = getFileUrl(fileUrl);
        return str.trim();
    }

    /**
     * 单个文件上传(指定文件名（带后缀）)
     *
     * @param file 上传的文件
     * @return 返回完整URL地址
     */
    public String uploadFile(MultipartFile file, String fileName) {
        try {
            InputStream inputStream = file.getInputStream();
            this.uploadFileToOSS(inputStream, fileName);
            return fileName;
        } catch (Exception e) {
            return "上传失败";
        }
    }

    /**
     * 多文件上传
     *
     * @param fileList 上传的文件列表
     * @return 返回图片URL列表
     */
    public List<String> uploadFile(List<MultipartFile> fileList) {
        String fileUrl = "";
        List<String> photoUrlList = new ArrayList<>();
        for (int i = 0; i < fileList.size(); i++) {
            fileUrl = uploadImgToOss(fileList.get(i));
            photoUrlList.add(getFileUrl(fileUrl));
        }
        return photoUrlList;
    }

    /**
     * 通过文件名获取文完整件路径
     *
     * @param fileUrl 文件路径
     * @return 完整URL路径
     */
    public String getFileUrl(String fileUrl) {
        if (fileUrl != null && fileUrl.length() > 0) {
            String[] split = fileUrl.split("/");
            String url = this.getUrl(this.fileDir + split[split.length - 1]);
            return url;
        }
        return null;
    }

    /**
     * 获取去掉参数的完整路径
     *
     * @param url 路径
     * @return 去掉参数的完整路径
     */
    private String getShortUrl(String url) {
        String[] imgUrls = url.split("\\?");
        return imgUrls[0].trim();
    }

    /**
     * 获得url链接
     *
     * @param key 键
     * @return url链接
     */
    private String getUrl(String key) {
        // 设置URL过期时间为20年 3600l* 1000*24*365*20
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 20);
        // 生成URL
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        if (url != null) {
            return getShortUrl(url.toString());
        }
        return null;
    }

    /**
     * 上传文件到oss
     *
     * @param file 文件
     * @return 文件路径
     */
    private String uploadImgToOss(MultipartFile file) {
        //1、限制最大文件为20M
        if (file.getSize() > 1024 * 1024 * 20) {
            return "图片太大";
        }

        if (file.getOriginalFilename() != null) {
            String fileName = file.getOriginalFilename();
            //文件后缀
            String suffix = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
            String uuid = UUID.randomUUID().toString();
            String name = uuid + suffix;

            try {
                InputStream inputStream = file.getInputStream();
                this.uploadFileToOSS(inputStream, name);
                return name;
            } catch (Exception e) {
                return "上传失败";
            }
        } else {
            return "上传的图片不能为空";
        }

    }


    /**
     * 上传文件到oss（指定文件名）
     *
     * @param instream 文件
     * @param fileName 文件名
     * @return 文件路径
     */
    private String uploadFileToOSS(InputStream instream, String fileName) {
        String ret = "";
        try {
            //创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(instream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getContentType(fileName.substring(fileName.lastIndexOf("."))));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);

            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            PutObjectResult putResult = ossClient.putObject(bucketName, fileDir + fileName, instream, objectMetadata);
            ret = putResult.getETag();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                if (instream != null) {
                    instream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    /**
     * 获取文件类型
     *
     * @param FilenameExtension 文件
     * @return 文件类型
     */
    private static String getContentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpeg";
        }
        if (FilenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase(".pptx") ||
                FilenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase(".docx") ||
                FilenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        if (FilenameExtension.equalsIgnoreCase(".pdf")) {
            return "application/pdf";
        }
        return "image/jpeg";
    }
}
